package org.rainbow.password;

import java.util.concurrent.atomic.AtomicInteger;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
    private Ehcache passwordRetryCache;

    public RetryLimitHashedCredentialsMatcher() {
        CacheManager cacheManager = CacheManager.newInstance(CacheManager.class.getClassLoader().getResource("ehcache.xml"));
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String)token.getPrincipal();

        Element element = passwordRetryCache.get(username);
        if(element == null) {
            element = new Element(username , new AtomicInteger(0));
            passwordRetryCache.put(element);
        }
        AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();
        if(retryCount.incrementAndGet() > 5) {
            logger.debug("密码验证错误超出5次，请稍后再试！！");
            
            throw new ExcessiveAttemptsException();
        }
        //========================================
        boolean matches = super.doCredentialsMatch(token, info);
        if(matches) {
        	logger.debug("=========清除缓存=======");
            passwordRetryCache.remove(username);
        }else {
        	logger.debug("=========登录失败=======");
		}
        
        return matches;
    }
}
